import {Component, OnInit, ChangeDetectionStrategy} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {SpinService} from '../../core/services/store/spin/spin.service';
import {Router} from '@angular/router';
import {LoginService} from '../../core/services/http/login/login.service';
import {WindowService} from '../../core/services/common/window.service';
import {fnCheckForm} from '../../utils/tools';
import {finalize} from 'rxjs/operators';
import {AuthKey, TokenPre, UserInfoKey} from '../../configs/constant';
import {AuthService} from '../../core/services/store/auth.service';
import {UserInfoService} from '../../core/services/store/user-info.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LoginComponent implements OnInit {
  validateForm!: FormGroup;

  constructor(private fb: FormBuilder, private spinService: SpinService,
              private router: Router, private dataService: LoginService,
              private windowServe: WindowService, private authService: AuthService,
              private loginUserInfoService: UserInfoService) {
  }

  submitForm(): void {
    // this.router.navigateByUrl('default');
    if (!fnCheckForm(this.validateForm)) {
      return;
    }
    const param = this.validateForm.getRawValue();
    this.spinService.setCurrentGlobalSpinStore(true);
    this.dataService.login(param).pipe(finalize(() => {
      this.spinService.setCurrentGlobalSpinStore(false);
    })).subscribe((res) => {
      this.windowServe.setStorage(AuthKey, TokenPre + res.token);
      this.loginUserInfoService.setLoginUserInfoMode({
        userId: res.userId,
        userName: res.userName,
      });
      this.authService.setAuthCode(this.authService.parsToken(TokenPre + res.token));
      this.authService.parsToken(res.token);
      this.windowServe.setStorage(UserInfoKey, JSON.stringify({
        userId: res.userId,
        userName: res.userName,
      }));
      this.router.navigateByUrl('default/file-manage');
    });
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [null],
    });
  }

}
